<template>
  <view class="apption">
    <scroll-view
      class="scroll-content"
      :scroll-y="true"
      :scroll-top="scrollTop"
      @scroll="handleScrollDebounced"
    >
      <view v-if="hotGoodsListData.length>0" class="uni-margin-wrap banner1">
        <swiper class="swiper" circular :indicator-dots="true" :autoplay="true">
          <swiper-item v-for="list,index of hotGoodsListData" :key="index">
            <image class="bannerImages1" :src="list.image"></image>
          </swiper-item>
        </swiper>
      </view>
      <view v-if="noticeData.length>0" class="noticeBar">
        <image class="ico_sound2" src="../../static/ico_sound2.gif"></image>
        <uni-notice-bar class="remindText" scrollable :speed="50" background-color="#fff" color="#000" :text="noticeData[0].content" />
      </view>
      <!-- <swiper class="announcement-bar" circular="true" vertical="true" autoplay="true" interval="5000" duration="1000">
        <block v-for="(item, index) in noticeData" :key="index">
          <swiper-item>
            <uni-notice-bar class="remindText" single show-icon background-color="#fff" color="#000" :text="item.content" />
          </swiper-item>
        </block>
      </swiper> -->
      <view :class="isClassAdded ? 'navRegular' : ''">
        <view class="dayTimeNav">
          <view class="prevDay" :class="dayTimeNavValue==1?'active':''" @click="dayTimeNavClickfun(1)">
            <image src="@/static/activepng.png" class="icoBg" />
            <view class="textTip"><icon class="ico1" />昨日甄选<icon class="ico2" /></view>
          </view>
          <view class="toDay" :class="dayTimeNavValue==2?'active':''" @click="dayTimeNavClickfun(2)">
            <image src="@/static/activepng.png" class="icoBg" />
            <view class="textTip"><icon class="ico1" />今日热卖<icon class="ico2" /></view>
          </view>
          <view class="prevDay" :class="dayTimeNavValue==3?'active':''" @click="dayTimeNavClickfun(3)">
            <image src="@/static/activepng.png" class="icoBg" />
            <view class="textTip"><icon class="ico1" />明日主推<icon class="ico2" /></view>
          </view>
        </view>
        <view class="dayTimeInfo">
          <view class="day">{{ currentTime }}</view>
          <view class="countdown">
            <view class="text">距结束</view>
            <view class="times"><template>{{ countdownValue.hours }}</template></view><view style="margin: 0 10rpx;">:</view>
            <view class="times"><template><template v-if="(countdownValue.minutes+'').length==1">0</template>{{ countdownValue.minutes }}</template></view><view style="margin: 0 10rpx;">:</view>
            <view class="times"><template><template v-if="(countdownValue.seconds+'').length==1">0</template>{{ countdownValue.seconds }}</template></view>
            <!-- <view class="shareBut">
              <view class="showshareBut"><icon class="icoShare" />分享</view>
              <button class="tipshareBut"  open-type="share">分享微信好友</button>
            </view> -->
          </view>
        </view>
        <view class="tabCommodity" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
          <view v-for="list of partitionData" :key="list.id" class="tabList" :class="list.id==partitionValue?'active':''" @click="partitionClick(list)">{{ list.name }}</view>
        </view>
      </view>
      <view v-if="goodsListData.length > 0" class="imageTextBox" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
        <view v-for="titleList,index of goodsListData" :key="index">
          <view v-if="titleList.goodsArr.length>0" class="classifyTitle">
            <icon class="ico1" />{{ titleList.cate_name }}<icon class="ico2" />
          </view>
          <view v-if="titleList.goodsArr.length>0" class="listBox">
            <view v-for="list,j of titleList.goodsArr" :key="j+'sub'" class="list">
              <!-- mode="widthFix" -->
              <image class="listImage" :src="list.logo"></image>
              <view class="tips_info" @click="commodityClick(list)">
                <image src="@/static/listbg.png" class="bg"></image>
                <view class="text">
                  <view class="oldPrice">¥{{ list.market_price }}</view>
                  <view class="price"><text class="symbol">¥</text>{{ list.discount_price }}</view>
                  <view v-if="list.is_pre==1" class="openTime">预售倒计时 {{ formatDate(list.end_time) }}</view>
                  <view v-if="list.is_pre==0" class="openTime">开团时间 {{ formatDate(list.put_time) }}</view>
                  <view class="residueNum">剩余数量 {{ list.stock }}</view>
                </view>
              </view>
              <button v-if="list.live_status===1" class="mini-btn statusBut" type="default" size="mini">直播中</button>
              <view class="contText">
                <view class="name" @click="commodityClick(list)">{{ list.title }}</view>
                <view class="downBox">
                  <button v-if="list.label" class="tuijianBut" type="default" size="mini">{{ list.label }}</button>
                  <view v-if="!list.label" />
                  <view class="shareBut">
                    <icon class="icoShare" />分享
                    <button class="wx-button" open-type="share" :data-obj="list">隐藏的分享按钮</button>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
  import { getApi, postApi } from "@/api/index.js"
  import moment from 'moment'
  
	export default {
    created() {
     //#ifdef MP-WEIXIN
     wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
     });
     //#endif
    },
		data() {
			return {
        loading: false,
				title: 'Hello',
				dayTimeNavValue: 2,
				countdownValue: {
					hours: 0,
					minutes: 0,
					seconds: 0
				},
        noticeData: [],
        hotGoodsListData: [],
        classifyData: [],
        partitionData: [] ,// 商品专区
				partitionValue: '',
        currentTime: '' ,// 当前时间
        goodsListData: [],
        shareOBj: {
          title: '',
          path: '',
          imageUrl: ''
        },
        startX: 0,
        moveX: 0,
        isSwiping: false,
        isInit: 1,// 滑动到最左边or最右边停止加载init()
        
        scrollTop: 0,
        isClassAdded: false, // 标记是否已达到目标位置
        threshold: 300 // 目标滚动位置

			}
		},
    // 其他数据和方法...
    onShareAppMessage(options) {
      if (options.from === 'button') {
        // 从按钮点击分享时的处理逻辑
        let item = options.target.dataset.obj; // 假设您的按钮有自定义数据属性data-obj来绑定商品数据
        console.log(item)
        return {
          title: item.title, // 商品标题
          path: `/pages/detail/detail?id=${item.id}`, // 商品详情页路径
          imageUrl: item.logo // 商品图片地址
        };
      }
    },
    // onShareTimeline(res) { //分享到朋友圈
    // console.log('res.分享到朋友圈')
    //  return {
    //   title: this.shareOBj.title,
    //   imageUrl: this.shareOBj.imageUrl
    //  }
    // },
		onLoad() {
      uni.setNavigationBarTitle({
        title: '爵美奢选·全球好物' // 设置为你想要显示的标题文本
      })
			this.currentTime = moment().format('YYYY-MM-DD')
			this.currentTimeReverse = moment().format('YYYY/MM/DD')
			this.initMounted()
			// this.init()
		},
		onShow() {
			// 每秒更新一次倒计时
			setInterval(this.countdown, 1000);
		},
		methods: {
      formatDate(date) {
        return moment(date).format('YYYY/MM/DD') // 格式化日期
      },
      // onShareAppMessage(res) {
      //     console.log('res.来自页面内分享按钮来自页面内分享按钮', res)
      //     if (res.from === 'button') {// 来自页面内分享按钮
      //       console.log(res.target)
      //       this.shareOBj.title = `/pages/detail/detail?id=` + res.target.dataset.shareid
      //       this.shareOBj.imageUrl = `/pages/detail/detail?id=` + res.target.dataset.shareid
      //       this.shareOBj.path = `/pages/detail/detail?id=` + res.target.dataset.shareid
      //     }
      // },
      initMounted(){
        // 获取分区
        postApi('/index/partition').then(res => {
          if(res.code === 1){
            this.partitionData = res.data
						this.partitionValue = res.data[0].id
            // 获取顶部幻灯片数据和首页分类数据
            postApi('/index/index').then(res => {
              if(res.code == 1){
                this.loading = false
                this.hotGoodsListData = res.data.banner
            		this.classifyData = res.data.classify
                this.init()
              }
            }).catch(err => {
              this.loading = false
            })
          }
        }).catch(err => {
        })
        // 获取公告
        postApi('/index/notice').then(res => {
          if(res.code === 1){
            this.noticeData = res.data
          }
        }).catch(err => {
        })
        
      },
      dayTimeNavClickfun(index){
				this.dayTimeNavValue = index
        if(index==1){
          this.currentTime = moment().subtract(1, 'days').format('YYYY-MM-DD');
        }
        if(index==2){
          this.currentTime = moment().format('YYYY-MM-DD')
        }
        if(index==3){
          this.currentTime = moment().add(1, 'days').format('YYYY-MM-DD')
        }
        this.init()
			},
      partitionClick(row){
				this.partitionValue = row.id
        this.init()
			},
			countdown() {
			  const now = new Date();
			  const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59); // 设置当天的结束时间为23:59:59
			  const diff = endOfDay - now; // 计算剩余时间
			 
			  // 如果当前时间已经超过了今天的23:59:59，则重新计算倒计时
			  if (diff < 0) {
			    this.countdown();
			    return;
			  }
			 
			  this.countdownValue.hours = Math.floor(diff / (1000 * 60 * 60));
			  this.countdownValue.minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
			  this.countdownValue.seconds = Math.floor((diff % (1000 * 60)) / 1000);
			  // 输出结果
			  // console.log(`${hours}小时${minutes}分钟${seconds}秒`);
			},
      // init(){
      //   this.goodsListData = []
      //   this.classifyData.forEach((list) => {
      //     setTimeout(() => {
      //       // console.log(list)
      //         let obj={
      //           partition: this.partitionValue,
      //           create_time: this.currentTime,
      //           cate_id: list.id,
      //           page: 1,
      //           limit: 200
      //         }
      //         postApi('/goods/goodsList', obj).then(res => {
      //           if(res.code === 1){
      //             this.loading = false
      //             this.goodsListData.unshift({
      //               cate_id: list.id,
      //               cate_name: list.title,
      //               goodsArr: res.data.list
      //             })
      //           }
      //         }).catch(err => {
      //           this.loading = false
      //         })
      //       })
      //       console.log(this.goodsListData)
      //     }, 500);
      // },
      async init(type){
        this.goodsListData = []
        const arrayToProcess = this.classifyData
        for (let i = 0; i < arrayToProcess.length; i++) {
          // 使用async函数等待接口调用结果
          const response = await this.callInterface(arrayToProcess[i]);
          console.log(response)
          // 将接口返回的数据添加到 goodsListData 中
          this.goodsListData.push({
            cate_id: arrayToProcess[i].id,
            cate_name: arrayToProcess[i].title,
            goodsArr: response.data.list
          });
        }
        // 所有接口调用完成后，这里的代码会执行
        // if(type==1){
        //   this.scrollTop = 300
        // }
        console.log('所有接口调用完成，goodsListData:', this.goodsListData);
      },
      callInterface(item) {
        // 这里是接口调用的逻辑，返回Promise
        return new Promise((resolve, reject) => {
          let obj={
            partition: this.partitionValue,
            create_time: this.currentTime,
            cate_id: item.id,
            page: 1,
            limit: 200
          }
          postApi('/goods/goodsList', obj).then(res => {
            if(res.code === 1){
              // this.loading = false
              // this.goodsListData.unshift({
              //   cate_id: list.id,
              //   cate_name: list.title,
              //   goodsArr: res.data.list
              // })
              resolve(res)
            }
          }).catch(err => {
            reject(error)
          })
        });
      },
      commodityClick(row){ // 跳转商品详情页，直播中则跳转直播url
        if(row.live_status===1){
          uni.navigateTo({
            url: `/pages/detail/detail?id=` + row.id
          })
        }else{
          uni.navigateTo({
            url: `/pages/detail/detail?id=` + row.id
          })
        }
      },
      touchStart(event) {
        this.startX = event.touches[0].clientX;
        this.moveX = this.startX;
        this.isSwiping = true;
      },
      touchMove(event) {
        // console.log('22222222222222222')
        // 在这里可以通过event.changedTouches获取移动中的触摸点信息
        if (!this.isSwiping) return;
        this.moveX = event.touches[0].clientX;
        // 防止误触，只有当水平滑动距离大于垂直滑动距离时才处理滑动
        if (Math.abs(this.moveX - this.startX) > Math.abs(event.touches[0].clientY - event.touches[0].clientY)) {
          this.isSwiping = true;
        } else {
          this.isSwiping = false;
        }
      },
      touchEnd(event) {
        if (this.isSwiping) {
          const diffX = this.moveX - this.startX;
          if (Math.abs(diffX) > 100) { // 设置滑动距离阈值，50可调整以适应真实场景
            if (diffX < 0) {
              // this.$emit('swipeleft');
              this.moveFun(2)
            } else {
              // this.$emit('swiperight');
              this.moveFun(1)
              
            }
          }
        }
        this.isSwiping = false;
      },
      moveFun(type){
        let indexCurrent = 0
        this.partitionData.forEach((list,index) => {
          if(list.id === this.partitionValue){
            if(type==1){
              if((index - 1) >= 0){
                indexCurrent = index - 1
                this.isInit = 1
              }else{
                indexCurrent = 0
                this.isInit--
              }
            }
            if(type==2){
              if((index + 1) <= 3){
                indexCurrent = index + 1
                this.isInit = 4
              }else{
                indexCurrent = 3
                this.isInit++
              }
            }
          }
        })
        // console.log('滑动后索引为',indexCurrent)
        // console.log('init计数为', this.isInit)
        this.partitionValue = this.partitionData[indexCurrent].id
        // console.log('滑动后id为', this.partitionValue)
        if(this.isInit > 4 || this.isInit < 1){
          // console.log('不执行init()')
        }else{
          // console.log('执行了init()')
          // 假设您想要滚动到距离页面顶部100像素的位置
          // this.scrollTop = 0
          this.init(1)
        }
      },
      // 滚动条事件
      // 监听滚动事件的方法
      handleScroll(e) {
        // this.scrollTop = e.detail.scrollTop;
        // if (this.scrollTop >= this.targetPosition) {
        //   this.isClassAdded = true;
        // }else{
        //   this.isClassAdded = false;
        // }
        const { scrollTop } = e.detail;
        // this.setData({ scrollTop });
        
        if (scrollTop >= this.threshold && !this.isClassAdded) {
          this.isClassAdded = true;
          // this.setData({ isClassAdded: true });
          // 给view元素添加class
        } else if (scrollTop < this.threshold && this.isClassAdded) {
          this.isClassAdded = false;
          // this.setData({ isClassAdded: false });
          // 移除view元素的class
        }
      },
      handleScrollDebounced(e){
        this.debounce(this.handleScroll(e), 200);
      },
      debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
          const later = () => {
            clearTimeout(timeout);
            func(...args);
          };
          clearTimeout(timeout);
          timeout = setTimeout(later, wait);
        };
      }
    }
	}
</script>

<style lang="scss" scoped>
  .scroll-content {
    height: 100vh;
    flex: 1;
    overflow-y: scroll;
  }
  
  .scroll-item {
    padding: 10px;
    border-bottom: 1px solid #ccc;
  }
	.apption {
    background-color: #fff;
    height: 100vh;
    ::v-deep swiper{
      height: 460rpx;
    }
    .banner1{
      .bannerImages1{
        width: 100%;
        height: 460rpx;
        background: #AAAAAA;
      }
      uni-swiper{
        height: 460rpx;
      }
      uni-image{
        width: 100%;
        height: 460rpx;
      }
    }
    .noticeBar{
      position: relative;
      .ico_sound2{
        position: absolute;
        top: 10rpx;
        left: 10rpx;
        width: 80rpx;
        height: 80rpx;
      }
    }
    .remindText{
      ::v-deep .uni-noticebar{
        width: 91%;
        margin-left: 9%;
      }
    }
    .announcement-bar {
      /* 公告栏样式 */
      height: 104rpx; /* 根据需要调整高度 */
    }
    .announcement-bar swiper-item {
     /* 滚动项样式 */
     // text-align: center;
     line-height: 50rpx; /* 与容器高度相同 */
    }
  //   .remindText{
  //     margin-bottom: 16rpx;
		// 	padding: 0 20rpx;
		// 	font-weight: 500;
		// 	font-size: 24rpx;
		// 	color: #202121;
  //     display: flex;
  //     align-items: center;

		// 	.icoSound{
		// 		margin-right: 16rpx;
		// 		width: 30rpx;
		// 		height: 24rpx;
		// 		display: inline-block;
		// 		background-image: url('@/static/ico_sound2.png');
		// 		background-size: 100% 100%;
		// 	}
		// }
    .navRegular{
      position: fixed;
      top: 0;
      left: 0;
      z-index: 9999;
      z-index: 9999;
      width: 100%;
      background: #fff;
    }
		.dayTimeNav{
			margin-bottom: 40rpx;
			padding: 0 20rpx 0 20rpx;
			height: 104rpx;
			line-height: 104rpx;
			text-align: center;
			display: flex;
			align-items: center;
			justify-content: space-between;
			background: #D0E3E1;
			border-radius: 0rpx 0rpx 0rpx 0rpx;
			box-sizing: border-box;
			font-weight: bold;
			font-size: 28rpx;
			color: #368A82;
			.prevDay{
				width: 33.33%;
				height: 104rpx;
        .icoBg{
          display: none;
        }
			}
			.toDay{
				width: 33.33%;
				height: 104rpx;
        .icoBg{
          display: none;
        }
			}
			.nextDay{
				width: 33.33%;
				height: 104rpx;
        .icoBg{
          display: none;
        }
			}
			.active{
				position: relative;
				.icoBg{
          display: block;
					position: absolute;
					left: 0;
					top: 0;
					width: 252rpx;
					height: 124rpx;
					z-index: 8;
				}
				.textTip{
					position: absolute;
					left: 0;
					top: 0;
					width: 252rpx;
					height: 124rpx;
					z-index: 9;
					color: #FFFFFF;
				}
				.ico1{
					margin-right: 12rpx;
					width: 22rpx;
					height: 16rpx;
					display: inline-block;
					background-image: url('@/static/ico_white.png');
					background-size: 100% 100%;
				}
				.ico2{
					margin-left: 12rpx;
					width: 22rpx;
					height: 16rpx;
					display: inline-block;
					background-image: url('@/static/ico_white.png');
					background-size: 100% 100%;
				}
			}
		}
		.dayTimeInfo{
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 40rpx;
			.day{
				color: #5C684B;
			}
			.countdown{
				display: flex;
				align-items: center;
				.text{
					margin-right: 20rpx;
				}
				.times{
					width: 42rpx;
					height: 42rpx;
					line-height: 42rpx;
					text-align: center;
					background: #63B3AB;
					border-radius: 8rpx 8rpx 8rpx 8rpx;
					font-size: 20rpx;
					color: #FFFFFF;
				}
				.shareBut{
					position: relative;
					margin-left: 20rpx;
					display: flex;
					align-items: center;
					overflow: hidden;
          font-size: 24rpx;
					.showshareBut{
						display: flex;
						align-items: center;
					}
					.tipshareBut{
						position: absolute;
						left: 0px;
						top: 0px;
						z-index: 9;
						opacity: 0;
					}
					.icoShare{
						margin-right: 12rpx;
						width: 42rpx;
						height: 42rpx;
						display: inline-block;
						background: #C6ADA1;
						background-image: url('@/static/ico_share.png');
						background-size: 32rpx 32rpx;
						background-repeat: no-repeat;
						background-position: center center;
						border-radius: 50%;
					}
				}
			}
		}
		.bannerType{
      padding: 20rpx;
      display: flex;
      flex-wrap: wrap;
      .images{
        width: 100%;
        height: 100%;
        background: #AAAAAA;
      }
      .list{
        position: relative;
        .text{
          position: absolute;
          top: 20rpx;
          left: 20rpx;
          height: 40rpx;
          line-height: 40rpx;
          padding: 0 10rpx;
          background: rgba(0,0,0,0.23);
          border-radius: 4rpx 4rpx 4rpx 4rpx;
          font-weight: 800;
          font-size: 20rpx;
          color: #FFFFFF;
          z-index: 5;
        }
      }
      .bannerImages1{
        width: 50%;
        height: 364rpx;
        padding-right: 4rpx;
        margin-bottom: 8rpx;
        box-sizing: border-box;
      }
      .bannerImages2{
        width: 50%;
        height: 364rpx;
        padding-left: 4rpx;
        margin-bottom: 8rpx;
        box-sizing: border-box;
      }
      .bannerImages3,.bannerImages4,.bannerImages5{
        width: 33.33%;
        height: 228rpx;
        margin-bottom: 8rpx;
        box-sizing: border-box;
      }
      .bannerImages3{
        padding-right: 5.33rpx;
      }
      .bannerImages4{
        padding-left: 2.66rpx;
        padding-right: 2.66rpx;
      }
      .bannerImages5{
        padding-left: 5.33rpx;
      }
    }
    .dayTime{
      padding: 0 20rpx 20rpx 20rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-weight: bold;
      font-size: 28rpx;
      .prevDay{
        width: 124rpx;
        height: 60rpx;
        text-align: center;
        line-height: 60rpx;
        background: linear-gradient( 180deg, #000000 0%, #2E2D2D 100%);
        border-radius: 32rpx 32rpx 32rpx 32rpx;
        font-weight: bold;
        font-size: 20rpx;
        color: #FFFFFF;
      }
      .nextDay{
        width: 124rpx;
        height: 60rpx;
        text-align: center;
        line-height: 60rpx;
        border-radius: 32rpx 32rpx 32rpx 32rpx;
        border: 2rpx solid #000000;
        font-weight: bold;
        font-size: 20rpx;
        color: #000000;
      }
    }
    .tabCommodity{
      padding: 40rpx 20rpx 20rpx 20rpx;
      display: flex;
      justify-content: space-between;
			border-bottom: 4rpx solid #F4F5F8;;
      .tabList{
        font-size: 30rpx;
      }
      .active{
				position: relative;
        font-weight: bold;
				&::after{
					content: '';
					position: absolute;
					bottom: -10rpx;
					left: 25%;
					width: 50%;
					height: 4rpx;
					background: #74C4BC;
					border-radius: 4rpx 4rpx 4rpx 4rpx;
				}
      }
    }
  }
</style>
